﻿/* Copyright AbstractFactory.cs Killian Bourrié
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License. */

namespace NPattern.AbstractFactory
{
    using System;
    using System.Linq;

    public sealed class AbstractFactory
    {
        private Type typeOfMaker;

        public AbstractFactory(Type typeOfMaker)
        {
            this.typeOfMaker = typeOfMaker;
        }

        public delegate void ObjectBuildingEventHandler(object sender, FactoryEventArgs args);

        public delegate void ObjectBuildedEventHandler(object sender, FactoryEventArgs args);

        public event ObjectBuildingEventHandler ObjectBuilding;

        public event ObjectBuildedEventHandler ObjectBuilded;

        public TObject Build<TObject>(object enumeration)
        {
            // Vérify if implements IMaker
            if (this.typeOfMaker.GetInterfaces().Contains(typeof(IMaker<TObject>)))
            {
                IMaker<TObject> customMaker = (IMaker<TObject>)Activator.CreateInstance(this.typeOfMaker);
                if (this.ObjectBuilding != null)
                {
                    this.ObjectBuilding(this, new FactoryEventArgs(enumeration, customMaker));
                }

                TObject instance = customMaker.Instance(enumeration);
                if (this.ObjectBuilded != null)
                {
                    this.ObjectBuilded(this, new FactoryEventArgs(enumeration, customMaker));
                }
                
                return instance;
            }
            else
            {
                throw new TypeIsNotMakerException();
            }
        }
    }
}
